package com.moss.cloud.remote.biz.service.impl;

import com.moss.cloud.common.base.model.po.SystemConfig;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.security.component.RedisTemplateOps;
import com.moss.cloud.remote.api.model.from.WXUserInfoFrom;
import com.moss.cloud.remote.api.model.from.WXUserTokenFrom;
import com.moss.cloud.remote.api.model.vo.WXCodeAccessToken;
import com.moss.cloud.remote.api.model.vo.WXUserInfo;
import com.moss.cloud.remote.api.model.vo.WXUserJSCode;
import com.moss.cloud.remote.biz.service.IWXService;
import com.moss.cloud.remote.biz.utils.WXUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 微信接口服务类
 *
 * @author 瑾年
 * @date 2023年3月31日
 */
@Slf4j
@Service
public class WXServiceImpl implements IWXService {

    private final RedisTemplateOps redisTemplateOps;

    public WXServiceImpl(RedisTemplateOps redisTemplateOps) {
        this.redisTemplateOps = redisTemplateOps;
    }

    /**
     * 用CODE换取access_token
     *
     * @param wxUserTokenFrom
     * @return
     */
    @Override
    public WXCodeAccessToken doGetToken(WXUserTokenFrom wxUserTokenFrom) {
        String appId = (String) redisTemplateOps.get(Constant.SYSTEM_CONFIG + Constant.WX_APP_ID);
        String secret = (String) redisTemplateOps.get(Constant.SYSTEM_CONFIG + Constant.WX_APP_SECRET);
        return WXUtil.doGetToken(appId, secret, wxUserTokenFrom.getCode());
    }

    /**
     * 用accessToken和openid获取用户信息
     *
     * @param wxUserInfoFrom
     * @return
     */
    @Override
    public WXUserInfo doGetUserInfo(WXUserInfoFrom wxUserInfoFrom) {
        return WXUtil.doGetUserInfo(wxUserInfoFrom.getAccess_token(), wxUserInfoFrom.getOpenId());
    }

    /**
     * JS_CODE获取openid
     *
     * @param wxUserTokenFrom
     * @return
     */
    public WXUserJSCode doGet(WXUserTokenFrom wxUserTokenFrom) {
        SystemConfig appId = (SystemConfig) redisTemplateOps.get(Constant.SYSTEM_CONFIG + Constant.WX_APP_ID);
        SystemConfig secret = (SystemConfig) redisTemplateOps.get(Constant.SYSTEM_CONFIG + Constant.WX_APP_SECRET);
        return WXUtil.doGet(appId.getConfigValue(), wxUserTokenFrom.getCode(), secret.getConfigValue());
    }
}
